package com.kkui.liuxin.controller;


import com.kkui.liuxin.service.MkdirService;
import com.kkui.liuxin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;


/**
 * @author kkui
 * @Description: 提供文件下载
 * @status: 512
 */
@Slf4j
@Controller
@RequestMapping("/api")
public class FileDown {

    @Resource
    UserService userService;
    @Resource
    MkdirService mkdirService;


    @PostMapping("/download")
    public void downLoad(@RequestParam("path") String path, HttpServletResponse response, @RequestHeader("Authorization") String authorization) throws FileNotFoundException, UnsupportedEncodingException {

        log.info(path);
        //通过mkdir获取父路径 ＋ 通过token获取id=>获取用户名 + 用户子路径
        File file = new File(mkdirService.getDefaultParentFolder() + userService.jwtGetUserId(authorization)
                + File.separator + path.replace("/",File.separator));
        if(!file.exists()){
            response.setStatus(512);
        }
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));


        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("{}",e);

        }

    }

}
